from  MatchDirectory.Model import BookUnit
from  MatchDirectory.Model import Book


root_path = ''

def exportBook(bookid):

    resarray = Book.find_all(" id = '{}' ".format(bookid))
    if len(resarray)<=0:
        print("未找到ID为{}的信息".format(bookid))
        return
    book = resarray[0]
    resList = BookUnit.find_all(where=("bookid = '{}' ".format(bookid)))
    print(len(resList))

    f = open("{rootpath}/{bookname}_{bookid}_title.txt".format(rootpath=root_path,bookid=bookid,bookname=book.name),mode='ab')
    fc = open("{rootpath}/{bookname}_{bookid}_content.txt".format(rootpath=root_path,bookid=bookid,bookname=book.name),mode='ab')

    for unit in resList:
        print(">> {} -> {}".format(unit.title,unit.content[0:10]))
        f.write(unit.title.encode())
        f.write("  <#{}#>".format(str(unit.id)).encode())
        f.write('\n'.encode())

        fc.write(unit.title.encode())
        fc.write('\n---{id}---\n'.format(id=unit.id).encode())
        fc.write(unit.content.encode())
        fc.write('\n'.encode())

    fc.close()
    f.close()


def exportBookList(bookid_list):
    for bookid in bookid_list:
        exportBook(bookid)

if __name__ == '__main__':
    root_path = "/Users/Rdxer/Documents"
    exportBookList([4687,14])